import { getFileListApi } from '@/services/file';
import useTableList from '@/utils/useTableList';
import { FileOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { Button, ButtonProps, Modal, Image, Table, Row, Form, Col, Input, Flex } from 'antd';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import React, { useState } from 'react';
import styles from './index.less';
import message from '@/utils/message';

interface SelectFileButtonProps {
  onSelect: (data: any[]) => void;
  buttonProps?: ButtonProps;
  multiple?: boolean;
  sourceType?: number;
}

const SelectImageButton: React.FC<SelectFileButtonProps> = ({
  onSelect,
  buttonProps,
  multiple = false,
  sourceType,
}) => {
  const [open, setOpen] = useState(false);
  const [selectRows, setSelectRows] = useState<any[]>([]);
  const { loading, datasource, total, page, pageSize, onFinish, onPageChange, form } = useTableList(
    {
      fetchApi: getFileListApi,
      extraParamsInfo: {
        fileType: 0,
        sourceType,
      },
    },
  );
  const onOpenSelect = () => {
    setOpen(true);
    setSelectRows([]);
    form.resetFields();
    onFinish({});
  };
  const columns: ColumnsType<any> = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      key: 'fileName',
    },
    {
      title: '预览',
      dataIndex: 'filePath',
      key: 'filePath',
      width: 200,
      render: (filePath, row) =>
        row.fileType === 0 ? <Image src={filePath} alt="file" width={'100%'} /> : '不支持预览',
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 150,
      render: (size: number) => {
        return `${(size / 1024).toFixed(2)} KB`;
      },
    },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time * 1000).format('YYYY-MM-DD HH:mm:ss');
      },
    },
  ];
  const onOk = () => {
    if (selectRows.length === 0) {
      message.warning('请至少选择一个文件');
      return;
    }
    setOpen(false);
    onSelect(selectRows);
    setSelectRows([]);
  };
  return (
    <>
      <Button type="primary" icon={<FileOutlined />} onClick={onOpenSelect} {...buttonProps}>
        选择文件
      </Button>
      <Modal
        title="选择图片文件"
        open={open}
        width={1000}
        centered
        onCancel={() => setOpen(false)}
        onOk={onOk}
      >
        <Row gutter={[30, 30]} style={{ padding: '15px 30px' }}>
          <div className={styles.search_box}>
            <Form
              form={form}
              onFinish={(v) => {
                setSelectRows([]);
                onFinish(v);
              }}
              onReset={() => {
                setSelectRows([]);
                onFinish({});
              }}
              labelCol={{
                span: 5,
              }}
              style={{ width: '100%' }}
            >
              <Row gutter={[20, 20]}>
                <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                  <Form.Item label="文件名称" name="fileName">
                    <Input placeholder="请输入文件名称" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={12} lg={12} xl={16} xxl={18}>
                  <Flex align="center" justify="flex-end" gap={15}>
                    <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                      查询
                    </Button>
                    <Button htmlType="reset" icon={<ReloadOutlined />}>
                      重置
                    </Button>
                  </Flex>
                </Col>
              </Row>
            </Form>
          </div>
          <div className={styles.table_box}>
            <Table
              columns={columns}
              dataSource={datasource}
              loading={loading}
              rowKey="id"
              scroll={{ x: 900, y: 'calc(100vh - 500px)' }}
              rowSelection={{
                type: multiple ? 'checkbox' : 'radio',
                onChange: (_, selectedRows) => {
                  setSelectRows(selectedRows);
                },
                selectedRowKeys: selectRows.map((item) => item.id),
              }}
              pagination={{
                current: page,
                pageSize: pageSize,
                total: total,
                showSizeChanger: false,
                showQuickJumper: true,
                onChange: onPageChange,
                showTotal: (total) => `共 ${total} 条数据`,
              }}
            />
          </div>
        </Row>
      </Modal>
    </>
  );
};

export default SelectImageButton;
